package apiFun

import (
	"cake-server/module"
	"cake-server/utils"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func LoginFun(c *gin.Context) {
	var user module.User
	err := c.ShouldBind(&user)
	if err != nil {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	result := module.DB.Where("account = ? and password = ?", user.Account, user.Password).First(&user)
	if result.RowsAffected > 0 {
		var token string
		token, err = utils.CreateToken(user.Account)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    400,
				"message": "生成token失败",
			})
			return
		}
		//更新token
		module.DB.Model(&user).Where("account = ?", user.Account).Update("token", token)
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "登录成功！",
			"token":   token,
			"data":    user,
		})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"message": "账号密码错误！",
		})
	}
}

func LoginRegister(c *gin.Context) {
	var user module.User
	err := c.ShouldBind(&user)
	result := module.DB.Where("account = ?", user.Account).First(&user)
	if result.RowsAffected > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"message": "账号已存在",
		})
		return
	}
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	now := time.Now()
	user.CreateTime = &now
	result = module.DB.Create(&user)
	if result.RowsAffected > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "添加成功",
			"data":    user,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"message": "添加失败",
			"err":     result.Error,
		})
	}
}

func LoginOut(c *gin.Context) {

}

type userSearch struct {
	module.User
	Limit
}

func GetUser(c *gin.Context) {
	var userSearch userSearch
	var users []module.User
	err := c.ShouldBindQuery(&userSearch)
	fmt.Println(userSearch)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	// 先获取总数
	var totalCount int64
	module.DB.Model(&module.User{}).Where("account like ? and name like ? and phone like ?", utils.VagueFormat(userSearch.Account), utils.VagueFormat(userSearch.Name), utils.VagueFormat(userSearch.Phone)).Count(&totalCount)
	result := module.DB.Order("create_Time asc").Where("account like ? and name like ? and phone like ?", utils.VagueFormat(userSearch.Account), utils.VagueFormat(userSearch.Name), utils.VagueFormat(userSearch.Phone)).Limit(userSearch.Limit.PageSize).Offset(userSearch.Limit.PageSize * (userSearch.PageIndex - 1)).Find(&users)

	if result.RowsAffected > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":       200,
			"message":    "获取成功",
			"data":       users,
			"totalCount": totalCount,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":       400,
			"message":    "无数据",
			"data":       users,
			"totalCount": totalCount,
		})
	}
}

func GetUser_Roles(c *gin.Context) {
	var userSearch userSearch
	var userList []module.User_Role_List
	var totalCount int64
	err := c.ShouldBind(&userSearch)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	module.DB.Model(&module.User{}).
		Where("account like ? and name like ? and phone like ?", utils.VagueFormat(userSearch.Account), utils.VagueFormat(userSearch.Name), utils.VagueFormat(userSearch.Phone)).
		Count(&totalCount)

	result := module.DB.Order("user.create_Time asc").
		Where("user.account like ? and user.name like ? and user.phone like ?", utils.VagueFormat(userSearch.Account), utils.VagueFormat(userSearch.Name), utils.VagueFormat(userSearch.Phone)).
		Limit(userSearch.Limit.PageSize).
		Offset(userSearch.Limit.PageSize * (userSearch.PageIndex - 1)).
		Table("user").
		Select("user.*,roles.name as roleName").
		Joins("left join roles on roles.id = user.role_id").
		Scan(&userList)

	if result.RowsAffected > 0 {
		fmt.Println(userList)
		c.JSON(200, gin.H{
			"code":       200,
			"message":    "查询成功",
			"data":       userList,
			"totalCount": totalCount,
		})
	} else {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "查询失败",
			"error":   result.Error,
		})
	}
}

// @Summary 添加用户
// @Description 详细描述
// @Tags 标签（用于分组）
// @Accept json
// @Produce json
// @Param account query string true "账号" default("admin")
// @Success 200 {object}
// @Router /api/addUser [post]
func AddUser(c *gin.Context) {
	var user module.User
	err := c.ShouldBind(&user)
	if err != nil {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	tx := module.DB.Begin()
	result := tx.Where("account = ?", user.Account).First(&user)
	if result.RowsAffected > 0 {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "账号已存在",
		})
		return
	}
	now := time.Now()
	user.CreateTime = &now
	result = tx.Create(&user)
	if result.RowsAffected > 0 {
		//添加中间表关系
		result = tx.Create(module.User_Role{
			UserId: user.Id,
			RoleId: user.RoleId,
		})
		if result.Error == nil {
			//提交事务
			tx.Commit()
			c.JSON(200, gin.H{
				"code":    200,
				"message": "添加成功",
			})
		} else {
			//回滚事务
			tx.Rollback()
			c.JSON(400, gin.H{
				"code":    400,
				"message": "添加失败",
				"err":     result.Error,
			})
		}
	} else {
		tx.Rollback()
		c.JSON(400, gin.H{
			"code":    400,
			"message": "添加失败",
			"err":     result.Error,
		})
	}
}
func UpdateUser(c *gin.Context) {
	err := module.DB.Transaction(func(tx *gorm.DB) error {
		var user module.User
		err := c.ShouldBind(&user)
		if err != nil {
			c.JSON(400, gin.H{
				"code":    400,
				"message": "参数错误",
			})
			return err
		}
		if err := tx.Save(user).Error; err != nil {
			return err
		}
		if err := tx.Where("user_id = ?", user.Id).Save(&module.User_Role{
			UserId: user.Id,
			RoleId: user.RoleId,
		}).Error; err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "修改失败",
			"err":     err,
		})
	} else {
		c.JSON(200, gin.H{
			"code":    200,
			"message": "修改成功",
		})
	}
}
func DeleteUser(c *gin.Context) {
	var ids []int
	err := c.ShouldBind(&ids)
	if err != nil {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	tx := module.DB.Begin()
	result := tx.Where("id in (?)", ids).Delete(&module.User{})
	if result.RowsAffected > 0 {
		result = tx.Where("user_id in (?)", ids).Delete(&module.User_Role{})
		if result.Error == nil {
			tx.Commit()
			c.JSON(200, gin.H{
				"code":    200,
				"message": "删除成功",
			})
		} else {
			tx.Rollback()
			c.JSON(400, gin.H{
				"code":    400,
				"message": "删除角色失败",
			})
		}
	} else {
		tx.Rollback()
		c.JSON(400, gin.H{
			"code":    400,
			"message": "删除失败",
			"err":     result.Error,
		})
		return
	}
}
